package com.lxj.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxj.security.common.utils.JwtTokenUtil;
import com.lxj.security.entity.LoginParam;
import com.lxj.security.entity.Permission;
import com.lxj.security.entity.User;
import com.lxj.security.mapper.PermisionMapper;
import com.lxj.security.mapper.UserMapper;
import com.lxj.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

@Service
@CacheConfig(cacheNames = "login")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public List<Permission> getPermissionsByUserId(Integer id) {
        return userMapper.getPermisionByUserId(id);
    }

    @Override
    @Cacheable(key = "#loginParams.username",unless = "#result == null")
    public String login(LoginParam loginParams) {
        String username = loginParams.getUsername();
        Assert.notNull(username,"账号不能为空");
        String password = loginParams.getPassword();
        Assert.notNull(password,"密码不能为空");
        User userByName = getUserByName(username);
        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
        if(matches){
            return jwtTokenUtil.generateToken(userByName);
        }
        return null;
    }

    @Override
    @Cacheable(key = "#id",unless = "#result == null")
    public User findAll(Integer id) {
        return userMapper.selectById(id);
    }

    private User getUserByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();//条件构造器
        wrapper.eq("username",username);
        User user=  userMapper.selectOne(wrapper);
        Assert.isTrue(user.getUsername()!=null,"您输入的账户不存在，或者有多个相同的账户");
        return user;
    }
}
